﻿using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Simple.Entity.Dto;
using Simple.Entity.Entity;
using Simple.Entity.Params;
using Simple.Entity.View;
using Simple.IRepository;
using Simple.IService;
using Simple.Tools;
using Simple.Tools.Security;
using Simple.Tools.Verify;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Extensions.Configuration;
using Simple.Tools.Extensions;
using Simple.Entity;
using Simple.Common;

namespace Simple.Service
/// <summary>
/// 版 本 钢易智企2.0 V 2.0.0 钢易智企2.0
/// Copyright (c) 2023 杭州钢易科技有限公司
/// 创建人：曾东明
/// 日 期：2024
/// 描 述：
/// </summary>
{
	public class UserService: BaseService,IUserService
	{
		[Autowired]

		protected IConfiguration configuration { get; set; }
		[Autowired]

		protected ILogger<UserService> logger { get; set; }

        [Autowired]
        protected IUserRepository userRepository { get; set; }

		[Autowired]

		protected IUserMenuRepository userMenuRepository { get; set; }

        [Autowired]
        public IRoleRepository userRoleRepository { get; set; }

        [Autowired]
        protected ISimpleMapper mapper { get; set; }
		/// <summary>
		/// 
		/// </summary>

        public UserService() { }

		/// <summary>
		/// 添加一个用户
		/// </summary>
		/// <returns></returns>
		public async Task<Common.BaseMessage> AddAsync(UserDto userDto)
		{
			var verify=userDto.Verify();

			if (verify.Item2==false)
			{
				return Bad500(verify.Item1);
			}
			if (await userRepository.AnyAsync(u=>u.IsDelete==false && u.Account==userDto.Account))
			{
				return Bad500("用户创建失败!");
			}
			if (userDto.RePassword!=userDto.Password)
			{
				return Bad500("两次输入的密码不一致!");
			}

			SysUserEntity sysUser = new SysUserEntity(true);

			mapper.Map(userDto,sysUser);

			//key 
			sysUser.Password= 20.Random();
			sysUser.SaltPassword= Security.AesEncrypt(userDto.Password,sysUser.Password);

			var result=await userRepository.CreateAsync(sysUser,0);
			if (result)
			{
				return Ok200("添加成功!");
			}
			return Bad400("添加失败!");

		}

		/// <summary>
		/// 登录
		/// </summary>
		/// <returns></returns>
		public async Task<Common.BaseMessage> LoginAsync(LoginParameter loginParameter)
		{
			userRepository.EnableLogger();
			if (!await userRepository.AnyAsync(u=>u.Account==loginParameter.Account))
			{
				return Bad400("登录失败账号不存在，请注册账号!");
			}

			SysUserEntity user=await userRepository.FirstOrDefaultAsync(u=>u.Account==loginParameter.Account);

			if (!Security.AesDescrypt(user.SaltPassword, user.Password, loginParameter.Password))
			{
				return Bad400("登录失败,密码或者账号不对!");
			}
			List<Claim> claims = new List<Claim>();

			claims.Add(new Claim("UserName",SimpleCheck.IsNullOrEmpty(user.UserName)?"":user.UserName));
			claims.Add(new Claim("Account", SimpleCheck.IsNullOrEmpty(user.Account)?"":user.Account));
			claims.Add(new Claim("Id", user.Id.ToString()));

			JwtSecurityToken token = new JwtSecurityToken(
					  issuer: configuration.GetValue<string>("JwtTokenOptions:Issuer"),
					  audience: configuration.GetValue<string>("JwtTokenOptions:Audience"),
					  claims: claims,
					  expires: DateTime.Now.AddMinutes(5),
					  signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue<string>("JwtTokenOptions:SecurityKey"))), SecurityAlgorithms.HmacSha256)
				  );

			UserInfoView info = new UserInfoView();
			mapper.Map(user,info);
			info.Token = new JwtSecurityTokenHandler().WriteToken(token);
                        
			return ReturnOk200(info,"登录成功!");
		}
		/// <summary>
		/// 重置密码
		/// </summary>
		/// <param name="Id"></param>
		/// <returns></returns>
		public async Task<Common.BaseMessage> RestPasswordAsync(long Id)
		{

			if (!await userRepository.AnyAsync(u => u.Id == Id && u.IsDelete == false))
			{
				return Bad500("更新失败!");
			}
			var user = await userRepository.FirstOrDefaultAsync(u => u.Id == Id && u.IsDelete == false);
			user.Password = 20.Random();//key
			string defaultPwd = configuration.GetValue<string>("SysDefaultPassword");
			user.SaltPassword = Security.AesEncrypt(defaultPwd,user.Password);
			var result = await userRepository.UpdateAsync(user);
			if (result)
			{
				return Ok200("更新成功!");
			}
			return Bad500("更新失败!");
		}

		/// <summary>
		/// 更新
		/// </summary>
		/// <param name="userDto"></param>
		/// <returns></returns>
		public async Task<Common.BaseMessage> UpdateAsync(long Id,UserDto userDto)
		{
			if (!await userRepository.AnyAsync(u => u.Id == Id && u.IsDelete == false))
			{
				return Bad500("更新失败!");
			}
			var user = await userRepository.FirstOrDefaultAsync(u => u.Id == Id && u.IsDelete == false);
			user.UserName=userDto.UserName;
			user.Account= userDto.Account;
			var result = await userRepository.UpdateAsync(user);

			if (result)
			{
				return Ok200("更新成功!");
			}
			return Bad500("更新失败!");
		}
		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="Id"></param>
		/// <returns></returns>
		public async Task<Common.BaseMessage> SoftDeleteAsync(long Id)
		{
			if (!await userRepository.AnyAsync(u=>u.Id==Id && u.IsDelete==false))
			{
				return Bad500("删除失败!");
			}

			var user=await userRepository.FirstOrDefaultAsync(u=>u.Id==Id && u.IsDelete==false);
			user.IsDelete= false;
			var result=await userRepository.UpdateAsync(user);

			if (result)
			{
				return Ok200("删除成功!");
			}
			return Bad500("删除失败!");

		}

		/// <summary>
		/// 查询用户
		/// </summary>
		/// <returns></returns>
		public async Task<Common.BaseMessage> GetPageAsync(UserParameter Params)
		{
			var query = userRepository.Query((q) =>
			{

				q.OrderBy(user=>user.CreationTime,SqlSugar.OrderByType.Desc);
			});
			return Ok200(await PageList<UserView>.CreateAsync(query,Params));
		}
	}
}
